package cn.sfa.common.quartzJob;

import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import microsoft.exchange.webservices.data.Appointment;
import microsoft.exchange.webservices.data.AppointmentType;
import microsoft.exchange.webservices.data.BodyType;
import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ExchangeVersion;
import microsoft.exchange.webservices.data.MessageBody;
import microsoft.exchange.webservices.data.SendInvitationsMode;
import microsoft.exchange.webservices.data.StringList;
import microsoft.exchange.webservices.data.TimeZoneDefinition;
import microsoft.exchange.webservices.data.WebCredentials;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.ConfigUtil;
import cn.sfa.entity.quartz.SaleQuartzMessage;
import cn.sfa.entity.routine.SaleMessagestake;
import cn.sfa.service.routine.CalendarService;
import cn.sfa.service.routine.ExChangeCalendarService;

/**
 * 
 * 类名称：QuartzJob 类描述：quartz定时任务 创建人：lenovo 创建时间：2012-2-14 下午9:40:42 修改备注：
 * 
 * @version v1.0
 */
public class ExChangeQuartzJob {

	Logger log = LoggerFactory.getLogger(ExChangeQuartzJob.class);
	
	private QuartzMessageService messageService;

	public QuartzMessageService getMessageService() {
		return messageService;
	}

	public void setMessageService(QuartzMessageService messageService) {
		this.messageService = messageService;
	}

	private static boolean isRuning = false;

	private static String ewsUrl = "";
	
	private static String domain = "";
	
	private static ExchangeService service;
	
	static {
		try {
			Configuration config = ConfigUtil
					.getXmlConfig(ExChangeCalendarService.class
							.getClassLoader().getResource("/sys_config.xml")
							.getPath());
			ewsUrl = config.getString("ews-url"); 
			domain = config.getString("emailDomain");
		} catch (ConfigurationException e) {
			throw new RuntimeException(e + "配置文件初始化ews-url错误");
		}

	}

	public static ExchangeService StartExchange(String username, String pwd) {

		ExchangeService service = new ExchangeService(
				ExchangeVersion.Exchange2010);
		ExchangeCredentials credentials = new WebCredentials(username , pwd);
		service.setCredentials(credentials);
		try {
			// 设置Url
			service.setUrl(new URI(ewsUrl));
		} catch (Exception e) {
		}
		return service;
	}

	/* 创建日程 */
	public void sendMessage() { 
		
		List<SaleQuartzMessage> list = messageService.queryUnSend();
		//System.out.println("查询" + list.size());  
		for (SaleQuartzMessage message : list) { 
			try { 
				if (CommonUtil.isEmpty(message.getLoginname())) {
					continue;
				}  
				service = StartExchange(message.getLoginname(),message.getUserpassword()); 
				
				Appointment appointment = new Appointment(service); 
				
				//设置时间
				Date startDate = new Date((message.getMESSAGETAKEDATE()
						.getTime() - 28800000));
				Date endDate = new Date(
						(message.getMESSAGETAKEDATE().getTime() - 28800000)); 

				appointment.setStart(startDate);
				appointment.setEnd(endDate);
				
				//设置标题和内容
				appointment.setSubject(message.getMESSAGETAKETITLE()); 
				appointment.setBody(new MessageBody(BodyType.HTML, message.getMESSAGECONTENT())); 
  
				//设置收件人
				appointment.getRequiredAttendees().add(message.getLoginname()+"@" + domain); 
				
				//设置分类名
				StringList categories = new StringList();
				categories.add(message.getMESSAGETYPE());
				appointment.setCategories(categories);  
				 
				appointment.save(SendInvitationsMode.SendToAllAndSaveCopy);
				try{
				messageService.setSended(message.getSALEMESSAGRSSTAKEID());
				}catch(Exception ex){
					log.error("日历将被重复发送:消息推送成功但是状态更新失败,可能产生重复数据"+ex.getMessage());
				}
				//System.out.println("发送成功");

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}  
	}

}
